package com.eastedu.superise.handler.basic;

import cn.hutool.core.collection.CollectionUtil;
import com.eastedu.repository.basic.ResourceSource;
import com.eastedu.repository.basic.mapper.BasicResourceMapper;
import com.eastedu.repository.basic.mapper.ResourceSourceMapper;
import com.eastedu.repository.basic.po.BasicResourcePO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import com.eastedu.utils.JsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

/**
 * 更新应用者
 * #91503 历史数据处理：历史资源的应用时间若为空值，则值统一刷为“首次创建日期、“首次创建时间-1h”～“首次创建时间”。不为空值的，不刷。
 *
 * @author zhangzhishuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BasicApplyTimeHistoricalDataHandler extends AbstractHistoricalDataHandler<BasicResourcePO> {

    private final ResourceSourceMapper resourceSourceMapper;
    private final BasicResourceMapper basicResourceMapper;


    @Override
    protected String getSql() {
        return """
                SELECT DISTINCT t1.* FROM t_basic_resource t1
                INNER JOIN t_resource_source t2 ON t1.id = t2.resource_id
                WHERE t2.apply_time_start IS NULL AND t1.audit_state = 1;
                """;
    }

    @Override
    public void callback(BasicResourcePO po) throws SQLException {

        List<ResourceSource> resourceSources = JsonUtil.parseList(po.getSourcesJson(), ResourceSource.class);
        long oneHourMill = 60 * 60 * 1000L;
        Long newApplyTimeEnd = po.getAuditTime() == null ? po.getCreateTime() : po.getAuditTime();
        Long newApplyTimeStart = newApplyTimeEnd - oneHourMill;
        resourceSources.forEach(o -> {
            Long applyTimeStart = o.getApplyTimeStart();
            if (Objects.isNull(applyTimeStart)) {
                o.setApplyTimeStart(newApplyTimeStart);
                o.setApplyTimeEnd(newApplyTimeEnd);
            }
        });
        po.setSourcesJson(CollectionUtil.isEmpty(resourceSources) ? null : JsonUtil.toJsonString(resourceSources));
        resourceSourceMapper.updateApplyTime(newApplyTimeStart, newApplyTimeEnd, po.getId());
        basicResourceMapper.updateSourceJsonByResourceId(po, po.getId().toString());
    }


}
